package com.smh.imagesearchmcpserver;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class ApiKeyInterceptor implements HandlerInterceptor {
    private static final String HEADER_NAME = "IMAGE_SEARCH_API_KEY";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String uri = request.getRequestURI();
        if (uri.equals("/sse") || uri.equals("/mcp/message")){
            return true;
        }


//        String apiKey = request.getHeader(HEADER_NAME);
//        if (apiKey == null) {
//            response.setStatus(HttpStatus.BAD_REQUEST.value());
//            response.getWriter().write("Missing API Key");
//            return false;
//        }
//        ApiKeyContext.setApiKey(apiKey);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        ApiKeyContext.clear();
    }
}